package com.wsp.service.service;

import com.wsp.apimanagement.pojo.dto.Result;
import com.wsp.apimanagement.pojo.entity.Module;
import com.wsp.apimanagement.pojo.entity.Source;
import com.wsp.apimanagement.pojo.entity.User;
import com.wsp.apimanagement.pojo.vo.IndexInfo;
import com.wsp.apimanagement.pojo.vo.UserModule;
import com.wsp.apimanagement.service.UserService;
import com.wsp.service.mapper.ModuleMapper;
import com.wsp.service.mapper.SourceMapper;
import com.wsp.service.mapper.UserMapper;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * Package: com.wsp.service.service
 * Description： TODO
 *
 * @Author: 巫思平
 * Copyright: Copyright (c) 2020
 * Version: 1
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    SourceMapper sourceMapper;
    @Autowired
    ModuleMapper moduleMapper;

    @Override
    public Result<User> findUserByOpenId(String openId) {
        User user = userMapper.findUserByOpenId(openId);
        if(user==null) {
            return null;
        }
        return Result.<User>builder().code(200).msg("SUCCESS").data(userMapper.findUserByOpenId(openId)).build();
    }

    public Result<IndexInfo> getIndexInfo(long userId) {
        final Integer maxSourceId = sourceMapper.getMaxSourceId();
        final int i = new Random().nextInt(maxSourceId);
        final List<Source> randomSource = sourceMapper.getRandomSource(4,i);
        final List<Module> moduleList = moduleMapper.getModuleByUserId(userId);
        return Result.<IndexInfo>builder().code(200).msg("SUCCESS").data(new IndexInfo(moduleList,randomSource)).build();
    }

    @Override
    public Result<User> insertUser(String openId, String userName, String userAvatar) {
        long userId = userMapper.insertUser(openId, userName, userAvatar);
        User user = new User();
        user.setUserId(userId);
        user.setOpenId(openId);
        user.setUserName(userName);
        user.setUserAvatar(userAvatar);
        user.setTotalLike(0);
        return Result.<User>builder().code(200).msg("SUCCESS").data(user).build();
    }
}
